/**
 * 入参
 *  type：1-指令新增   2-簿记新增    3-详情  4-交收
    info：type=3||4时，需回填字段
    onRef：组件指针
    getInfo：通过onRef，调用getInfo方法，获取各字段的值，在getInfo中完成校验，若校验不通过，返回undefined
    reset：通过onRef，调用reset方法，清空页面字段
    productOnChange：产品变更事件，输出当前产品ID，若无则为undefined；
    portfolioOnChange：组合变更事件，输出当前组合ID，若无则为undefined；
    tradingcodeOnChange：证券代码变更事件，输出当前证券code，若无则为undefined。
 */
import React, { PropTypes, PureComponent, Fragment } from 'react';
import {
  PrimaryC,
  DATA_ENTRY,
  InputNumberC,
  ModalC,
  PrimaryGhostC,
  codeType,
  TradingDirectC,
  TradingTypeC,
  InputC,
  SingleDateC,
  AdvancedSearch,
  ProductGroupSepC,
  SelectC,
  NoQueryC,
  TableC,
  FirstHeaderC,
  SecondHeaderC,
  TradingMarketC,
} from '../../../../comps';
import { Form } from '@ant-design/compatible';
import '@ant-design/compatible/assets/index.css';
import { Row, Col, Card, Input, Button, message, Table, Divider, DatePicker, Select, Modal } from 'antd';
import style from './index.less';
import { connect } from 'dva';
import OrderFormC from './orderFormC';
import { uniqueKey } from '../../../../utils/commonFunc';
const { TextArea } = Input;
const FormItem = Form.Item;
const FormItemLayout = {
  labelCol: {
    xl: { span: 10, offset: 0 },
    xxl: { span: 8, offset: 0 },
  },
  wrapperCol: {
    xl: { span: 13, offset: 0 },
    xxl: { span: 15, offset: 0 },
  },
};

class AddOrderC extends PureComponent {
  static defaultProps = {
    portfolioOnChange: () => {},
    productOnChange: () => {},
    tradingcodeOnChange: () => {},
  };
  state = {
    info: undefined, //详情
    type: undefined, //当前指令的类型type：1-指令新增   2-簿记新增    3-簿记详情
    isShow: false, //二次确认模态框显示隐藏
    querys: {}, //二次确认详情数据
    isCanOrder: true, //组合是否可以下达 默认可以
    trailColumns: [], //试算结果列表
    trailDataSource: [], //试算结果数据
    trailModel: false, //试算模态框
    productCode: undefined, //产品code
    portfolioCode: undefined, //组合code
    uid: '',
  };
  componentDidMount() {
    this.props.onRef(this);
    const uid = uniqueKey();
    uid.then((r) => {
      this.setState({ uid: r });
    });
  }
  //用户点击下达或确定按钮
  onOk = () => {
    const { type, money, position, info } = this.props;
    if (!this.state.isCanOrder && type == 1) {
      message.warning(this.props.errorSetMsg);
      return;
    }
    const data = this.orderForm.getInfo();
    //校验页面数据
    if (!data) return;
    data.uid = this.state.uid;
    // 点击了中签按钮
    if (type == 5 && info) {
      this.beLuckyNumber({
        fee: data.trade17.fee || 0, // 费用计算逻辑未完全梳理清楚，后续用户有真正需求时再添加费用计算相关逻辑,
        quantity: data.quantity,
        id: info.id,
      });
      return;
    }

    if (type == 1) {
      if (this.state.isShow) {
        this.confirmOk(data); //二次确认的确定 点击按钮
      } else {
        //指令下达需要二次确认
        this.setState({
          querys: data,
          isShow: true,
        });
      }
    } else {
      //簿记无需二次确认 直接请求后端
      this.confirmOk(data);
    }
  };
  //用户点击了中签
  beLuckyNumber = (params) => {
    const { dispatch, type } = this.props;
    dispatch({
      type: 'bondOfflineM/luckyNumber',
      payload: {
        ...params,
      },
      callback: (res) => {
        if (res && res.code == 0) {
          message.success('中签成功!');
          this.props.onCancel('refresh'); //通知父组件刷新
        } else {
          message.error(res ? res.msg || res.message : '中签请求失败!');
        }
      },
    });
  };
  //用户点击取消
  onCancel = () => {
    this.orderForm.reset();
    this.setState({
      isCanOrder: true,
    });
    this.props.onCancel();
  };
  confirmOk = (params) => {
    //指令下达 簿记保存请求后台
    const { dispatch, type } = this.props;
    let url = type == 1 ? 'bondOfflineM/orderSave' : 'bondOfflineM/tradeBookSave';
    if (type == 2) {
      //簿记下达
      params.method = '0';
    }
    params.type = '17';
    dispatch({
      type: url,
      payload: {
        ...params,
      },
      callback: (res) => {
        if (res && res.success) {
          if (type == 2) {
            //簿记下达成功
            this.props.onOk();
            this.onCancel(); //初始化form表单
          } else {
            //指令下达成功
            this.onCancel(); //初始化form表单
            this.handleCancel(); //关闭模态框
          }
          message.success(type == 1 ? '指令下达成功!' : '簿记下达成功!');
        } else {
          message.error(res ? res.message || res.errorMsg : type == 1 ? '指令下达失败!' : '簿记下达失败!');
        }
        const uid = uniqueKey();
        uid.then((r) => {
          this.setState({ uid: r });
        });
      },
    });
  };
  //二次确认取消按钮 关闭模态框
  handleCancel = () => {
    this.setState({
      isShow: false,
      querys: {},
    });
  };
  // 二次确认modal框
  showModal = () => {
    const { querys, isShow } = this.state;
    const { loading } = this.props;
    const modalProps = {
      visible: isShow,
      title: '确认指令下达',
      width: 700,
      height: 1000,
      className: 'confirmOrder',
      confirmLoading: loading.effects['bondOfflineM/orderSave'] === true,
    };
    return (
      <ModalC {...modalProps} onOk={this.onOk} onCancel={this.handleCancel}>
        <OrderFormC type={'3'} info={querys} />
      </ModalC>
    );
  };

  queryIsAccountConfigured = (value) => {
    if (value) {
      this.props.dispatch({
        //校验组合下是否有组合配置
        type: 'isAccountConfiguredM/queryIsAccountConfigured',
        payload: {
          portId: value,
        },
        callback: (data) => {
          if (data.result) {
            this.setState({
              isCanOrder: true,
            });
          } else {
            this.setState({
              isCanOrder: false,
            });
            message.warning(data.msg);
          }
        },
      });
    } else {
      this.setState({
        isCanOrder: true,
      });
    }
  };
  //试算按钮点击
  trialOnClick = () => {
    const {
      type,
      user: { currentUser },
    } = this.props;
    const data = this.orderForm.getInfo();
    //校验页面数据
    if (!data) return;
    if (type == 2) {
      //簿记下达
      data.method = '0';
    }
    data.type = '17';
    (data.productCode = this.state.productCode), //产品code
      (data.portfolioCode = this.state.portfolioCode), //组合code
      (data.tenant = currentUser.tenant), //租户code
      (data.businessType = '17');
    this.setState({ trailModel: true }, () => {
      this.props.dispatch({
        type: 'trailM/trialData',
        payload: data,
        callback: (res) => {
          if (res) {
            this.setState({
              trailColumns: res.columns,
              trailDataSource: res.dataSource,
            });
          } else {
            this.setState({
              trailColumns: [],
              trailDataSource: [],
            });
          }
        },
      });
    });
  };
  //试算结果列表优化
  trailColumnsChange = (data) => {
    if (data) {
      data?.map((item) => {
        if (item.key == 'ruleDesc') {
          item.ellipsis = true;
        } else {
          item.width = '125px';
        }
      });
    }
    return data;
  };
  //试算结果
  showTrail = () => {
    const { trailModel, trailColumns, trailDataSource } = this.state;
    const newTrailColumns = this.trailColumnsChange(trailColumns);
    return (
      <ModalC
        visible={trailModel}
        title='试算结果'
        width={1200}
        onOk={() => {
          this.setState({ trailModel: false });
        }}
        onCancel={() => {
          this.setState({ trailModel: false });
        }}
      >
        <TableC
          columns={newTrailColumns}
          dataSource={trailDataSource}
          loading={this.props.loading.effects['trailM/trialData'] === true}
          scroll={{ y: '231px' }}
          rowKey='id'
          hidePage={true}
        />
      </ModalC>
    );
  };

  //获取组合code
  portfolioCode = (e) => {
    if (e) {
      this.setState({ portfolioCode: e });
    } else this.setState({ portfolioCode: undefined });
  };
  //获取产品code
  productCode = (e) => {
    if (e) {
      this.setState({ productCode: e });
    } else this.setState({ productCode: undefined });
  };
  render() {
    const { loading, type } = this.props;
    return (
      <div>
        <div className={'backBg'}>
          <OrderFormC
            type={this.props.type}
            portfolioOnChange={(e) => {
              this.props.portfolioOnChange(e);
              if (this.props.type == '1') this.queryIsAccountConfigured(e); //指令下达的时候进行校验组合是否配置
            }}
            tradingcodeOnChange={this.props.tradingcodeOnChange}
            portfolioCode={this.portfolioCode}
            productCode={this.productCode}
            onRef={(ref) => {
              this.orderForm = ref;
            }}
            info={this.props.info}
          />
        </div>
        {type < 3 ? (
          <div style={{ marginTop: '20px' }} className={style.btnOperate}>
            {/* {this.props.type == '2' && <PrimaryC
                                loading={this.props.loading.effects['trailM/trialData'] === true}
                                onClick={() => this.trialOnClick()}
                                title={'试算'}
                                style={{ marginRight: "10px" }}
                            />} */}
            <PrimaryC
              loading={loading.effects['bondOfflineM/tradeBookSave'] === true || loading.effects['bondOfflineM/orderSave'] === true}
              onClick={this.onOk}
              title={this.props.type == 1 ? '下达' : '确定'}
            />
            <PrimaryGhostC onClick={this.onCancel} title='取消' style={{ marginLeft: '10px' }} />
          </div>
        ) : null}
        {this.state.isShow ? <div>{this.showModal()}</div> : null}
        {this.state.trailModel && this.showTrail()}
      </div>
    );
  }
}
export default connect(({ bondOfflineM, userM: user, loading, trailM, isAccountConfiguredM }) => ({
  bondOfflineM,
  user,
  loading,
  trailM,
  errorSetMsg: isAccountConfiguredM.msg,
  isAccountConfiguredM,
}))(Form.create()(AddOrderC));
